package webbrow.member.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import webbrow.member.model.MemberService;
import webbrow.member.model.MemberVO;

@Controller
public class MemberController {
	@Resource(name = "memberServiceImpl")
	private MemberService memberService;

	// 회원 가입
		@RequestMapping("/registerInven.inven")
		public ModelAndView registerMember(MemberVO mvo) throws SQLException {
			uploadImg(mvo);
			memberService.registerMember(mvo);
			//System.out.println("register controller : "+mvo.getSaveImage());
			return new ModelAndView("home");
		}

		// 로그인
		@RequestMapping("/loginMember.inven")
		public String loginMember(HttpSession session, MemberVO vo)
				throws SQLException {
			//System.out.println(vo);
			MemberVO rvo = memberService.loginMember(vo);
			if(rvo!=null){
				int result = memberService.confirmDropout(vo.getId());
				if(result==1){
					return "dropout.member";
				}else{
					session.setAttribute("mvo", rvo);
					return "redirect:/home.inven";
				}
			}else{
				return "login_fail.member";
			}
			
		}
		
	// 아이디 중복확인
	@RequestMapping("/isExistId.inven")
	@ResponseBody
	public int isExistId(String id) throws SQLException{
		String message="true";
		System.out.println("controller isExistId");
		 int result=memberService.isExistId(id);
		 System.out.println("isE:"+result);
		 /*if(result==1){
			 message="false";
		 }*/
		return result;
	}
	// 이메일 중복확인 - 기존 회원일 경우
	@RequestMapping("/isExistEmail.inven")
	@ResponseBody
	public int isExistEmail(MemberVO mvo) throws SQLException{
		System.out.println("controller isExistEmail");
		 int result=memberService.isExistEmail(mvo);
		 System.out.println("isE:"+result);
		 /*if(result==1){
			 message="false";
		 }*/
		return result;
	}
	// 이메일 중복확인 : 회원가입
			@RequestMapping("/isExistEmailReg.inven")
			@ResponseBody
			public int isExistEmailReg(String email) throws SQLException{
				System.out.println("controller isExistEmail");
				 int result=memberService.isExistEmailReg(email);
				 System.out.println("isE:"+result);
				 /*if(result==1){
					 message="false";
				 }*/
				return result;
			}
	// 파일 크기 검사
	public ModelAndView confirmImgSize(File file) {
		return null;
	}

	// 파일 업로드
	public void uploadImg(MemberVO vo) {
		//System.out.println("fileUpload..이름:"+vo.getUserName());
		String path="C:\\java-kosta\\servers\\webbrow-tomcat\\webapps\\webbrow-ver1.0\\userpics\\";
				MultipartFile mFile=vo.getUploadFile();
				System.out.println(mFile.getSize()); //file size
				System.out.println(mFile.getOriginalFilename()); //파일명
				System.out.println(mFile.getName()); //파라미터 이름
				String orgImage = mFile.getOriginalFilename();
				if(orgImage!=""){
					vo.setOrgImage(orgImage);
					String saveImage = System.currentTimeMillis()+"_"+orgImage;
					vo.setSaveImage(saveImage);
					//업로드할 원본 파일을 이동시킬 파일 객체를 생성
					File copyFile=new File(path+saveImage);
					try {
						mFile.transferTo(copyFile);
						System.out.println("file upload ok...."+copyFile.getPath());
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}else{
					System.out.println("선택한 파일이 없습니다.");
				}
	}
		

	// 로그아웃
	@RequestMapping("/logoutMember.inven")
	public String logoutMember(HttpSession session, MemberVO vo)
			throws SQLException {
		System.out.println(vo);
		if (session != null) {
			if (session.getAttribute("mvo") != null) {
				session.invalidate();
			}

		}
		return "redirect:/home.inven";
	}

	@RequestMapping("/showMyInfo.inven")
	public ModelAndView showMyInfo(String id) throws SQLException {
		System.out.println("controller");
		return new ModelAndView("update.member", "vo", memberService.showMyInfo(id));
	}

	// 회원 정보 수정
	@RequestMapping("/updateInven.inven")
	public String updateMember(HttpSession session, MemberVO vo)
			throws SQLException, Exception, Exception {
		MemberVO mvo = (MemberVO) session.getAttribute("mvo");
		String path="C:\\java-kosta\\servers\\webbrow-tomcat\\webapps\\webbrow-ver1.0\\userpics\\";
		MultipartFile mFile=vo.getUploadFile();
		if(mFile!=null&&mFile.isEmpty()==false){
			String orgImage=mFile.getOriginalFilename();
			File deleteImage=new File(path+mvo.getSaveImage());
			deleteImage.delete();	
			// 기존에 있던 이미지를 삭제
			vo.setOrgImage(orgImage);
			// 시간_파일명으로 저장 
			String saveImage=System.currentTimeMillis()+"_"+orgImage;
			vo.setSaveImage(saveImage);
			File copyFile=new File(path+saveImage);
			// 업로드..
			mFile.transferTo(copyFile);
		}
		
		if(mFile.isEmpty()==true){
			vo.setSaveImage(mvo.getSaveImage()); //원래 세이브 이미지를 세션에 담긴 세이브이미지로 세팅.
		}				
		System.out.println(vo);		
		String id = mvo.getId();
		vo.setId(id);
		memberService.updateMember(vo);
		session.setAttribute("mvo", vo);
	
		return "redirect:/home.inven";
	}

	// 회원 탈퇴
		@RequestMapping("/secessionMember.inven")
		public String secessionMember(String id,HttpSession session) throws SQLException{
			MemberVO mvo = (MemberVO) session.getAttribute("mvo");
			String path="C:\\java-kosta\\servers\\webbrow-tomcat\\webapps\\webbrow-ver1.0\\userpics\\";
			File deleteImage=new File(path+mvo.getSaveImage());
			deleteImage.delete();	
			memberService.secessionMember(id);
			session.invalidate();
			// 기존에 있던 이미지를 삭제
			return "dropout.member";
		}

	// 사용자 요청에의한 기본 정보 보기
	public ModelAndView showMemberInfo(MemberVO vo) {
		return null;
	}
	@RequestMapping("/checkPassword.inven")
	@ResponseBody
	public String checkPassword (String id, String email) throws SQLException{
		 //System.out.println("controller isExistEmail "+id+email);
		 String result=memberService.checkPassword(id, email);
		 if(result==null){
			 result="fail";
		 }
		 //System.out.println(result);
		return result;
	}
}

